//
//  RequestServer.m
//  ChinaMerchantBank
//
//  Created by chen wei on 13-6-28.
//  Copyright (c) 2013年 xguanjia. All rights reserved.
//

#import "RequestServer.h"
#import "ASIHTTPRequest.h"
#import "JSON.h"
#import <CommonCrypto/CommonDigest.h>

@implementation RequestServer
static RequestServer* _instance;
static const int kHttpErrorCode = 1001;
static const int kJsonErrorCode = 1002;
static const int kFileErrorCode = 1003;
+ (RequestServer *)instance {
    if (nil == _instance) {
		_instance = [[RequestServer alloc] init];
	}
	return _instance;
}

#pragma mark ---- 类私有方法 ----
- (NSString*)serverUrl {
    NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
    
    NSString *serverUrl = [server objectForKey:@"current_ServerUrl"];
    if (serverUrl == nil) {

//        serverUrl = @"http://192.168.0.35:80/businessSchool";
        serverUrl = @"http://203.166.160.25:8078/businessSchool";
        
        
        
        [server setObject:serverUrl forKey:@"current_ServerUrl"];
    }
    NSLog(@"%@",serverUrl);
    serverUrl = [serverUrl stringByAppendingString:@"/ServiceServlet"];
    return serverUrl;
}

- (void)doDeletageCallBack:(id)delegate
                  withCode:(NSNumber*)code
               withMessage:(NSString*)message
                  withData:(id)data {
	if ([delegate respondsToSelector:@selector(requestFinished:withMessage:withData:)]) {
		[delegate requestFinished:code withMessage:message withData:data];
  	}
}

#pragma mark ---- ASIHTTPRequests ----
- (void)messageDidFinish:(ASIHTTPRequest *)request
{
    //停止等待光标
    [self stopWaitCursor];
    
    NSError *error = [request error];
    
	id delegate = [[request userInfo] objectForKey:@"delegate"];
    
	if (error) {
        //执行delegate中的callback函数
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:kHttpErrorCode] withMessage:[error localizedDescription] withData:nil];
        return;
	}
    
    
    NSDictionary* headers = [request responseHeaders];
    NSString* code = [headers objectForKey:@"code"];
    
    if (code && [code intValue] != 0) {
        NSString* oldMessage = [headers objectForKey:@"Message"];
        
        NSData *newData = [NSData dataWithBase64EncodedString:oldMessage];
        NSString *message = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
        NSString *responseString = [request responseString];
        //    int reqJsonLen = strlen(responseString);
        //	[MAUserDefaults messageFlow:reqJsonLen];
        NSLog(@"--------Response data=%@--------", responseString);
        
        //SBJSON *json = [SBJSON new];
        NSDictionary *responseDictionary = [responseString JSONValue];
        
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:[code intValue]] withMessage:message withData:[responseDictionary objectForKey:@"data"]];
        return;
    }
    NSString *responseString = [request responseString];
    //    int reqJsonLen = strlen(responseString);
    //	[MAUserDefaults messageFlow:reqJsonLen];
    NSLog(@"--------Response data=%@--------", responseString);
    
	//SBJSON *json = [SBJSON new];
	NSDictionary *responseDictionary = [responseString JSONValue];//[json objectWithString:responseString error:&error];
	
	//[json release];
    
	if (error) {
        //执行delegate中的callback函数
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:kJsonErrorCode] withMessage:[error localizedDescription] withData:nil];
        return;
	}
	
    //执行delegate中的callback函数
    [self doDeletageCallBack:delegate withCode:0 withMessage: [responseDictionary objectForKey:@"message"] withData:[responseDictionary objectForKey:@"data"]];
    return;
}

- (void)didFailed:(ASIHTTPRequest *)request
{
    //停止等待光标
    [self stopWaitCursor];
    
    id delegate = [[request userInfo] objectForKey:@"delegate"];
    NSFileHandle* fileHandle = [[request userInfo] objectForKey:@"fileHandle"];
    if (fileHandle) {
        [fileHandle closeFile];
    }
    NSError *error = [request error];
    
    [request cancel];
    [request clearDelegatesAndCancel];
    
        //执行delegate中的callback函数
    [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:kHttpErrorCode] withMessage:[error localizedDescription] withData:nil];
    return;
}

- (void)uploadFileDidFinish:(ASIHTTPRequest *)request
{    
    NSError *error = [request error];
	id delegate = [[request userInfo] objectForKey:@"delegate"];    
    
    NSDictionary* headers = [request responseHeaders];
    NSString* code = [headers objectForKey:@"Code"];
    
    if (code && [code intValue] != 0) {
        NSString* oldMessage = [headers objectForKey:@"Message"];
        NSData *newData = [NSData dataWithBase64EncodedString:oldMessage];
        NSString *message = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
        
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:[code intValue]] withMessage:message withData:nil];
        return;
    }
    NSString *responseString = [request responseString];
    NSLog(@"%@",responseString);
    
    //	SBJSON *json = [SBJSON new];
    //	NSDictionary *responseDictionary = [json objectWithString:responseString error:&error];
	
    NSDictionary *responseDictionary = [responseString JSONValue];
    
	if (error) {
        //执行delegate中的callback函数
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:kJsonErrorCode] withMessage:[error localizedDescription] withData:nil];
        return;
	}
	
	
    //执行delegate中的callback函数
    [self doDeletageCallBack:delegate withCode:0 withMessage:[responseDictionary objectForKey:@"message"] withData:[responseDictionary objectForKey:@"file_id"]];
	
    return;
}

- (NSString *)md5HexDigest:(NSString*)input
{
    //HexinFinance
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

#pragma mark ---- 类公共方法 ----
- (void)doActionAsync:(int)viewInstanceId
           withAction:(NSString*)actionName
       withParameters:(id)parameters
         withDelegate:(id<RequestServerDelegate>)delegate {
//判断网络状态
    [self startWaitCursor];
    NSURL *url = [NSURL URLWithString:[self serverUrl]];
    
    NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
    NSString *serverUrl = [server objectForKey:@"current_ServerUrl"];

    NSURL *url1 = [NSURL URLWithString:serverUrl];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:2];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request1 returningResponse: &response error: nil];
    if (response == nil) {
        [self stopWaitCursor];
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:1000001] withMessage:Nil withData:nil];
        return;
    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    // 组织报文头
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
    [request addRequestHeader:@"te_method" value:@"doAction"];
    [request addRequestHeader:@"te_version" value:@"1.2"];
    [request addRequestHeader:@"party_id" value:@"moa"];
    [request setTimeOutSeconds:30];
    // 组织报文体
//    NSDictionary* parameter = [NSDictionary dictionaryWithObjectsAndKeys:actionName,@"actionName",
//                               [NSString stringWithFormat:@"%@|%@", [parameters JSONRepresentation],[self md5HexDigest:[NSString stringWithFormat:@"HexinFinance%@",[parameters JSONRepresentation]]]], @"parameters",[NSNumber numberWithInt:viewInstanceId],@"viewId",nil];

    NSDictionary* parameter = [NSDictionary dictionaryWithObjectsAndKeys:actionName,@"actionName",
                               parameters, @"parameters",[NSNumber numberWithInt:viewInstanceId],@"viewId",nil];
    
    const char *utfString = [[parameter JSONRepresentation] UTF8String];
    if (utfString) {
        [request setPostBody:[NSData dataWithBytes:utfString length:strlen(utfString)]];
        NSLog(@"serverUrl:%@, asynchRequest:%s", [self serverUrl], utfString);
    }
    else {
        return;
    }
    NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:delegate,@"delegate",nil];
    [request setUserInfo:userInfo];
    [request setUseCookiePersistence:YES];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(messageDidFinish:)];
    [request setDidFailSelector:@selector(didFailed:)];
    [request setDidReceiveDataSelector:nil];
    [request startAsynchronous];
}

- (void)doActionAsync2:(int)viewInstanceId
           withAction:(NSString*)actionName
       withParameters:(id)parameters
         withDelegate:(id<RequestServerDelegate>)delegate;
{
    [self startWaitCursor];
    NSURL *url = [NSURL URLWithString:[self serverUrl]];
    
    NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
    NSString *serverUrl = [server objectForKey:@"current_ServerUrl"];
    
    NSURL *url1 = [NSURL URLWithString:serverUrl];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:1];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request1 returningResponse: &response error: nil];
    if (response == nil) {
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alert show];
        [self stopWaitCursor];
        return;
    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    // 组织报文头
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
    [request addRequestHeader:@"te_method" value:@"doAction"];
    [request addRequestHeader:@"te_version" value:@"1.2"];
    [request addRequestHeader:@"party_id" value:@"moa"];
    [request setTimeOutSeconds:30];
    // 组织报文体
     
    NSDictionary* parameter = [NSDictionary dictionaryWithObjectsAndKeys:actionName,@"actionName",
                               parameters, @"parameters",[NSNumber numberWithInt:viewInstanceId],@"viewId",nil];
    
    
    const char *utfString = [[parameter JSONFragment] UTF8String];
    if (utfString) {
        [request setPostBody:[NSData dataWithBytes:utfString length:strlen(utfString)]];
        NSLog(@"serverUrl:%@, asynchRequest:%s", [self serverUrl], utfString);
    }
    else {
        return;
    }
    NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:delegate,@"delegate",nil];
    [request setUserInfo:userInfo];
    [request setUseCookiePersistence:YES];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(messageDidFinish:)];
    [request setDidFailSelector:@selector(didFailed:)];
    [request setDidReceiveDataSelector:nil];
    [request startAsynchronous];

}

- (void)doActionAsync3:(int)viewInstanceId
           withAction:(NSString*)actionName
       withParameters:(id)parameters
         withDelegate:(id<RequestServerDelegate>)delegate {
    //判断网络状态
    //    NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
    //
    //    NSString *serverUrl = [server objectForKey:@"current_ServerUrl"];
    //    hostRech =[Reachability reachabilityWithHostName:serverUrl];
    //    [hostRech startNotifier];
    //    if (NO==[hostRech startNotifier]) {
    //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    //        [alert show];
    //        return;
    //    }
    
    //开始等待光标
    [self startWaitCursor];
    NSURL *url = [NSURL URLWithString:[self serverUrl]];
    
    NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
    NSString *serverUrl = [server objectForKey:@"current_ServerUrl"];
    
    NSURL *url1 = [NSURL URLWithString:serverUrl];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:1];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request1 returningResponse: &response error: nil];
    if (response == nil) {
        //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        //        [alert show];
        [self stopWaitCursor];
        return;
    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    // 组织报文头
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
    [request addRequestHeader:@"te_method" value:@"doAction"];
    [request addRequestHeader:@"te_version" value:@"1.2"];
    [request addRequestHeader:@"party_id" value:@"moa"];
    [request setTimeOutSeconds:30];
    // 组织报文体
    NSDictionary* parameter = [NSDictionary dictionaryWithObjectsAndKeys:actionName,@"actionName",
                               parameters, @"parameters",[NSNumber numberWithInt:viewInstanceId],@"viewId",nil];
    
    const char *utfString = [[parameter JSONRepresentation] UTF8String];
    if (utfString) {
        [request setPostBody:[NSData dataWithBytes:utfString length:strlen(utfString)]];
        NSLog(@"serverUrl:%@, asynchRequest:%s", [self serverUrl], utfString);
    }
    else {
        return;
    }
    NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:delegate,@"delegate",nil];
    [request setUserInfo:userInfo];
    [request setUseCookiePersistence:YES];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(messageDidFinish:)];
    [request setDidFailSelector:@selector(didFailed:)];
    [request setDidReceiveDataSelector:nil];
    [request startAsynchronous];
}

- (void)doActionAsyncWithoutWaitCursor:(int)viewInstanceId
           withAction:(NSString*)actionName
       withParameters:(id)parameters
         withDelegate:(id<RequestServerDelegate>)delegate {
    
    NSURL *url = [NSURL URLWithString:[self serverUrl]];
    
//    NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
//    NSString *serverUrl = [server objectForKey:@"current_ServerUrl"];
//    
//    NSURL *url1 = [NSURL URLWithString:serverUrl];
//    NSURLRequest *request1 = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:2];
//    NSHTTPURLResponse *response;
//    [NSURLConnection sendSynchronousRequest:request1 returningResponse: &response error: nil];
//    if (response == nil) {
//        
//        //    if (serverUrl.length <= 0) {
//        //        serverUrl = @"http://192.168.1.105:80/cmbapp";
//        //    }
//        //    hostRech =[[Reachability reachabilityWithHostName:serverUrl] retain];
//        //    [hostRech startNotifier];
//        //    if (NO==[hostRech startNotifier]) {
//        
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alert show];
//        [alert release];
//        [self stopWaitCursor];
//        return;
//    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    // 组织报文头
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
    [request addRequestHeader:@"te_method" value:@"doAction"];
    [request addRequestHeader:@"te_version" value:@"1.2"];
    [request setTimeOutSeconds:60];
    // 组织报文体
    NSDictionary* parameter = [NSDictionary dictionaryWithObjectsAndKeys:actionName,@"actionName",
                               [NSString stringWithFormat:@"%@|%@", [parameters JSONRepresentation],[self md5HexDigest:[NSString stringWithFormat:@"HexinFinance%@",[parameters JSONRepresentation]]]], @"parameters",[NSNumber numberWithInt:viewInstanceId],@"viewId",nil];
    
    const char *utfString = [[parameter JSONRepresentation] UTF8String];
    if (utfString) {
        [request setPostBody:[NSData dataWithBytes:utfString length:strlen(utfString)]];
        NSLog(@"serverUrl:%@, asynchRequest:%s", [self serverUrl], utfString);
    }
    else {
        return;
    }
    NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:delegate,@"delegate",nil];
    [request setUserInfo:userInfo];
    [request setUseCookiePersistence:YES];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(messageDidFinish:)];
    [request setDidFailSelector:@selector(didFailed:)];
    [request setDidReceiveDataSelector:nil];
    [request startAsynchronous];
}

- (void)uploadFileAsync:(NSString*)filePath
           withDelegate:(id<RequestServerDelegate>)delegate {
    @try {

        NSUserDefaults *server = [NSUserDefaults standardUserDefaults];
        NSString *serverUrl1 = [server objectForKey:@"current_ServerUrl"];
        
        NSURL *url1 = [NSURL URLWithString:serverUrl1];
        NSURLRequest *request1 = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:0.5];
        NSHTTPURLResponse *response;
        for (int i =0; i < 3;i++ ) {
            [NSURLConnection sendSynchronousRequest:request1 returningResponse: &response error: nil];
            if (response != nil) {
                break;
            }
        }
        
        NSString *serverUrl = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"current_ServerUrl"]];
        NSURL *url = [NSURL URLWithString:[serverUrl stringByAppendingString:@"/UploadFilesServlet"]];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        // 组织报文头
        [request setRequestMethod:@"POST"];
        
        
        NSString *fileNameString = [[filePath componentsSeparatedByString:@"/"] lastObject];
        
        const char *utfString = [fileNameString UTF8String];
        NSData *requestData = [NSData dataWithBytes:utfString length:strlen(utfString)];
        NSString *message = [requestData base64Encoding];
        
        [request addRequestHeader:@"fileName" value:message];
        [request addRequestHeader:@"filepath" value:@"jokesAttachment"];
        [request setTimeOutSeconds:30];
        // 组织报文体
        NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:delegate,@"delegate",nil];
        [request setUserInfo:userInfo];
        
        [request setPostBodyFilePath:filePath];
        [request setShouldStreamPostDataFromDisk:YES];
        [request setDelegate:self];
        request.showAccurateProgress = YES;
        [request setUploadProgressDelegate:self];
        [request setDidFinishSelector:@selector(uploadFileDidFinish:)];
        [request setDidFailSelector:@selector(didFailed:)];
        [request setDidReceiveDataSelector:nil];
        [request startAsynchronous];

	}
	@catch (NSException * e) {
        [self doDeletageCallBack:delegate withCode:[NSNumber numberWithInt:kHttpErrorCode] withMessage:[e reason] withData:nil];
	}
    
}
- (void) startWaitCursor {
    BSAppDelegate *appDelegate = (BSAppDelegate*)[[UIApplication sharedApplication] delegate];
	[appDelegate startLoading];
}

- (void) stopWaitCursor {
    BSAppDelegate *appDelegate = (BSAppDelegate*)[[UIApplication sharedApplication] delegate];
	[appDelegate stopLoading];
}

@end
